import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

/**
 * @author xingzhiwen
 * @date 2021/9/14
 * @ddescription:
 */
@SuppressWarnings({"all"})

public class SocketTcp03Client {
    public static void main(String[] args) throws IOException {
        //1.连接服务端(ip 端口
            //如果；连接成功，返回socket对象
        Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
        System.out.println("客户端+socket返回 = " + socket.getClass());
        //连接上后，生成socket，通过socket。getoutputstream 得到和socket对象关联的输出流
        OutputStream outputStream = socket.getOutputStream();
        //通过输出流，写入数据到数据通道
        //字符流
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        bufferedWriter.write("hello world字符流");
        //插入换行符，表示写入结束
        bufferedWriter.newLine();//要求对方用readline来读
        //需要手动刷新，否则不会写入通道
        bufferedWriter.flush();
        //获取socket相关联的输入流，读取数据，并显示
        InputStream inputStream = socket.getInputStream();

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String s = bufferedReader.readLine();
        System.out.println(s);
        //设置结束标志

        //关闭流对象和socket，必须
        bufferedReader.close();
        bufferedWriter.close();
        socket.close();

        System.out.println("客户端结束");
    }
}
